package com.guigu.dealservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guigu.common.utils.R;
import com.guigu.dealservice.dto.Equipment;
import com.guigu.dealservice.dto.User;
import com.guigu.dealservice.entity.BargainIntention;
import com.guigu.dealservice.entity.Order;
import com.guigu.dealservice.feign.MyEquipmentFeign;
import com.guigu.dealservice.feign.MyUserFeign;
import com.guigu.dealservice.service.BargainIntentionService;
import com.guigu.dealservice.service.OrderService;
import com.guigu.userservice.vo.BusinessmanEquipmentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  砍价表
 * </p>
 *
 * @author janecraft
 * @since 2025-10-17
 */
@RestController
@RequestMapping("/dealservice/bargainIntention")
public class BargainIntentionController {

    @Autowired
    private BargainIntentionService bargainIntentionService;

    @Autowired
    private MyUserFeign myUserFeign;

    @Autowired
    private OrderService orderService;

    @Autowired
    private MyEquipmentFeign myEquipmentFeign;


    //砍价设备
    @PostMapping("/bargainIntentionAdd")
    public R bargainIntentionAdd(@RequestBody BargainIntention bargainIntention){
        try {
            bargainIntention.setBargainStatus(0);
            boolean save = bargainIntentionService.save(bargainIntention);
            if (save) {
                return R.ok().success(true).code(20000).message("砍价成功");
            }
            return R.error().success(false).code(20002).message("砍价失败");
        } catch (Exception e) {
            if (e.getMessage().contains("Duplicate entry") && e.getMessage().contains("uk_user_equipment")) {
                return R.error().success(false).code(20001).message("你已砍价过了");
            }
            return R.error().success(false).code(20002).message("砍价失败");
        }
    }

    //根据用户id和设备id查询砍价记录
    @GetMapping("/bargainIntentionList/{userId}/{equipmentId}")
    public R bargainIntentionList(@PathVariable("userId") Long userId, @PathVariable("equipmentId") Integer equipmentId) {
        QueryWrapper<BargainIntention> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.eq("equipment_id", equipmentId);
        BargainIntention one = bargainIntentionService.getOne(wrapper);
        return R.ok().data("bargainIntention", one);
    }

    /**
     * 前台-根据设备id去查询该设备下面的砍价记录信息
     * */
    @GetMapping("/selectBargainIntentionByEqId/{id}")
    public R selectBargainIntentionByEqId(@PathVariable("id") Integer id){

        QueryWrapper<BargainIntention> bargainIntentionQueryWrapper = new QueryWrapper<>();
        bargainIntentionQueryWrapper.eq("equipment_id",id);


        List<BargainIntention> list = bargainIntentionService.list(bargainIntentionQueryWrapper);

        for (BargainIntention bargainIntention:list){

            //远程调用-根据用户id查询返回用户名称
            User user = myUserFeign.queryUserById(Math.toIntExact(bargainIntention.getUserId()));
            if (user!=null){
                bargainIntention.setUserName(user.getUserName());
            }
        }
        return R.ok().data("list",list);
    }

    /**
     * 前台-修改砍价表的状态为（同意）并且添加到订单表
     *
     * */
    @PutMapping("/updateBargainIntentionStatusOne/{id}")
    public R updateBargainIntentionStatusOne(@PathVariable("id") Long id,@RequestBody BargainIntention bargainIntention){

        bargainIntention.setBargainStatus(1);
        bargainIntention.setReplyTime(LocalDateTime.now());

        boolean b = bargainIntentionService.updateById(bargainIntention);


        //添加到订单表
        Order order = new Order();
        order.setBuyerId(bargainIntention.getUserId());
        order.setSellerId(id);
        order.setEquipmentId(bargainIntention.getEquipmentId());
        order.setOrderAmount(bargainIntention.getIntentionPrice());
        order.setDepositAmount(bargainIntention.getOriginalPrice().multiply(new BigDecimal("0.3")));
        //砍价后的总价格
        BigDecimal finalPrice = bargainIntention.getIntentionPrice();
        //计算定金
        BigDecimal depositAmount = finalPrice.multiply(new BigDecimal("0.3"));
        //尾款（成交价 - 定金）
        BigDecimal balanceAmount = finalPrice.subtract(depositAmount);
        order.setBalanceAmount(balanceAmount);
        order.setOrderStatus(0);
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        orderService.save(order);

        if (b==true)
            return R.ok().code(20000).message("已同意").data("success", true);
        return R.error().code(20001).message("同意失败").data("success", false);
    }

    /**
     * 前台-修改砍价表的状态为（同意）并且添加到订单表
     *  设备id
     * */
    @PutMapping("/updateBargainIntentionStatusOne2/{id}")
    public R updateBargainIntentionStatusOne2(@PathVariable("id") Integer id){

        BargainIntention bargainIntention = bargainIntentionService.getById(id);
        bargainIntention.setBargainStatus(1);
        bargainIntention.setReplyTime(LocalDateTime.now());

        boolean b = bargainIntentionService.updateById(bargainIntention);

        Equipment equipment = myEquipmentFeign.selectEquipmentDxById(bargainIntention.getEquipmentId());


        //添加到订单表
        Order order = new Order();
        order.setBuyerId(bargainIntention.getUserId());
        order.setSellerId(equipment.getUserId());
        order.setEquipmentId(bargainIntention.getEquipmentId());
        order.setOrderAmount(bargainIntention.getIntentionPrice());
        order.setDepositAmount(bargainIntention.getOriginalPrice().multiply(new BigDecimal("0.3")));
        //砍价后的总价格
        BigDecimal finalPrice = bargainIntention.getIntentionPrice();
        //计算定金
        BigDecimal depositAmount = finalPrice.multiply(new BigDecimal("0.3"));
        //尾款（成交价 - 定金）
        BigDecimal balanceAmount = finalPrice.subtract(depositAmount);
        order.setBalanceAmount(balanceAmount);
        order.setOrderStatus(0);
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        orderService.save(order);

        if (b==true)
            return R.ok().code(20000).message("已同意").data("success", true);
        return R.error().code(20001).message("同意失败").data("success", false);
    }


    /**
     * 前台-修改砍价表的状态为（拒绝）
     * */
    @PutMapping("/updateBargainIntentionStatusTwo")
    public R updateBargainIntentionStatusTwo(@RequestBody BargainIntention bargainIntention){

        bargainIntention.setBargainStatus(2);
        bargainIntention.setReplyTime(LocalDateTime.now());

        boolean b = bargainIntentionService.updateById(bargainIntention);
        if (b==true)
            return R.ok().code(20000).message("已拒绝").data("success", true);
        return R.error().code(20001).message("拒绝失败").data("success", false);
    }

    /**
     * 前台-修改砍价表的状态为（拒绝）
     * */
    @PutMapping("/updateBargainIntentionStatusTwo2/{eid}")
    public R updateBargainIntentionStatusTwo2(@PathVariable Integer eid){
        BargainIntention bargainIntention = bargainIntentionService.getById(eid);

        bargainIntention.setBargainStatus(2);
        bargainIntention.setReplyTime(LocalDateTime.now());

        boolean b = bargainIntentionService.updateById(bargainIntention);
        if (b==true)
            return R.ok().code(20000).message("已拒绝").data("success", true);
        return R.error().code(20001).message("拒绝失败").data("success", false);
    }

    /**
     * 后台-分页查询设备砍价列表
     * @param id
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/bargainIntentionPageList/{id}/{pageNum}/{pageSize}")
    public R bargainIntentionPageList(@PathVariable("id") Integer id, @PathVariable("pageNum") Integer pageNum, @PathVariable("pageSize") Integer pageSize) {
        return bargainIntentionService.bargainIntentionPageList(id, pageNum, pageSize);
    }

  }
